import net from "net";
import TCP_Client from './TCP_Client.js';
import memDB from './memDB.js';
import { DEVICES } from "./publicValue.js";
import { updateDeviceStatus, writeRealData } from "./publicMethod.js";
import AK3300S from "./AK3300S.js";
import AK3300YC from "./AK3300YC.js";
import VX1300TN from "./VX1300TN.js";


//636f6d33017000000005;
const port = 7006;
let tcpServer = net.createServer();
tcpServer.on('listening', () => {
    console.debug('TCPServer is listening on port', port);
});
tcpServer.on('connection', (socket) => {

    console.info(socket.remoteAddress + '连接到服务器成功');
    let link = new TCP_Client(socket);
    link.on('release', (obj) => {
        console.log('释放连接', obj.sn);
        updateDeviceStatus(obj.sn, false);
        obj = null;

    });
    link.on('register', (obj) => {
        let db_device = memDB.getDevice(obj.sn);
        if (db_device == null) {
            console.log('设备不存在');
            obj.close();
            return;
        }
        updateDeviceStatus(obj.sn, true);
        if(db_device.model=='AK3300S'){
            let device= new AK3300S(obj.sn,obj);
             device.setReadInterval(db_device.interval);
             device.setAddr(db_device.addr);
            device.on('realData',async (sn,data)=>{
                writeRealData(sn,data);
            }); 
            DEVICES.set(obj.sn,device);
        }else if(db_device.model=='AK3300YC'){
            let device= new AK3300YC(obj.sn,obj);
            device.setReadInterval(db_device.interval);
            device.setAddr(db_device.addr);
            device.on('realData',async (sn,data)=>{
                writeRealData(sn,data);
            }); 
            DEVICES.set(obj.sn,device);
        }else if(db_device.model=='VX1300TN'){
            let device= new VX1300TN(obj.sn,obj);
            device.setReadInterval(db_device.interval);
            device.setAddr(db_device.addr);
            device.on('realData',async (sn,data)=>{
                writeRealData(sn,data);
            }); 
            DEVICES.set(obj.sn,device);
        }
    });


    //  let hec115t=new HEC115T(socket,'12345678901234567890123456789012');

    //  hec115t.on('release',(obj)=>{
    //         console.log('释放连接',obj.sn);
    //         obj=null;
            
    //     });
    // hec115t.on('register',(obj)=>{
    //     obj.on('realData',async (param)=>{
    //         updateLampRealData(param);
    //     });
    //     console.log('注册成功',obj.sn);
    //     TCP_DEVICES_MAP.set(obj.sn,obj);
    // });

});
tcpServer.on('error', (err) => { console.error('TCP服务出现错误 原因:', err.message); });
tcpServer.listen(port, '0.0.0.0');
export default tcpServer;